<template>
  <div class="newPosterIndex">
    <c-title :hide="false" :text='`海报中心`'></c-title>
    <div class="searchTop">
      <van-search v-model="keywork" placeholder="请输入搜索关键词" @search="searchMethod" />
    </div>
    <div class="tabsNav">
      <div class="tabsNavLis" @click="tapType(item.id)" :class="[active == item.id ? 'mda' : '']" v-for="(item, index) in info.type_list" :key="index">{{ item.value }}</div>
    </div>
    <div class="childTabs">
      <div class="left">
        <div class="tabChild" :class="[labelSelect == item.id ? 'mdalabel' : '']" v-for="(item, index) in info.label_list" :key="index" @click="tapLabel(item.id)">{{ item.name }}</div>
      </div>
      <div class="right" @click="showInMethod">
        筛选
        <img src="https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/newPoster%2Fselect.png" alt="" />
      </div>
    </div>
    <div class="posterList" v-if="info.poster_list && info.poster_list.data.length > 0">
      <div class="posterLis" v-for="(item, index) in info.poster_list.data" :key="index" @click="showPoster(item, index)">
        <img :src="item.design_img_url" alt="" v-if="item.design_img_show == 1"/>
        <img :src="item.background_change_url" alt="" v-else/>
        <div class="title">{{ item.title }}</div>
      </div>
    </div>
    <van-popup v-model="show" position="right" :style="{ height: '100%', width: '83%' }">
      <div class="rightBox">
        <div class="title">标签</div>
        <div class="tipsBox">
          <div class="tipslis" @click="chooseTag(item)" :class="[item.id == poplabel ? 'modeS' : '']" v-for="(item, index) in popupList" :key="index">
            <div class="modeSImg"></div>
            {{ item.name }}
          </div>
        </div>
        <div v-if="popupPage < popupLast" @click="popupMore">点击加载更多</div>
        <div class="btn">
          <div class="cancel" @click="cancelTap">取消</div>
          <div class="confirm" @click="confirmTap">确定</div>
        </div>
      </div>
    </van-popup>
    <van-popup v-model="fmPosterShow" class="poster-popup-class" :close-on-click-overlay="false" @close="closeFm" get-container="body">
      <div class="fmPoster">
        <img class="minimg" @click="scrollLeft" :src="showPosterInd == 0 ? leftImg1 : leftImg" alt="" />
        <div class="contenBox" v-longpress="{ cb: langClick, time: 500, iosUnable: true }">
          <div class="closeIcon" @click="closeFm"></div>
          <img
            class="fm"
            v-if="info.poster_list && info.poster_list.data && info.poster_list.data[showPosterInd]"
            :src="info.poster_list.data[showPosterInd].background_poster_url ? info.poster_list.data[showPosterInd].background_poster_url : info.poster_list.data[showPosterInd].background_change_url"
            alt=""
          />
          <div v-if="info.poster_list && info.poster_list.data && info.poster_list.data[showPosterInd].background_poster_url" class="btnTxt" @click="creatPoster">长按图片，保存到手机</div>
          <div v-else class="btn" @click="creatPoster">生成海报</div>
        </div>
        <img class="minimg" @click="scrollRight" :src="showPosterInd >= (info.poster_list && info.poster_list.data.length - 1) ? rightImg1 : rightImg" alt="" />
      </div>
    </van-popup>
    <yz_goodsPoster @finish="finish" @finishDefaultImg="finish" :plugin_name="`posterCenter`" v-model="posterShow" :posterData="posterData" :defaultImg="defaultImg"></yz_goodsPoster>
  </div>
</template>
<script>
import yz_goodsPoster from "components/ui_components/yz_goodsPoster";
import { scrollMixin } from "utils/mixin";
import { Toast } from "vant";
export default {
  mixins: [scrollMixin], //加载更多
  data() {
    return {
      keywork: "",
      // 已选类型
      active: 0,
      show: false,
      info: [],
      // 已选标签
      labelSelect: 0,
      poplabel: "",
      // 弹窗列表数组
      popupList: [],
      popupPage: 1,
      popupLast: 1,
      // 海报是否显示
      posterShow: false,
      // 前端生成图片参数
      posterData: {
        poster_data: null,
        background: {}
      },
      // 已生成的图片参数
      defaultImg: "",
      // 选择显示的海报封面索引
      showPosterInd: 0,
      fmPosterShow: false,
      childImgaeBase: "",
      leftImg: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/images%2FposterCenter%2Fleft.png",
      leftImg1: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/images%2FposterCenter%2Fleft2.png",
      rightImg: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/images%2FposterCenter%2Fright.png",
      rightImg1: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/images%2FposterCenter%2Fright2.png",
      is_record: false,
      toastPoster:null,

      isLoadMore: true,
      page: 1,
      total_page: 0
    };
  },
  activated() {
    this.getData();
  },
  methods: {
    // 保存图片
    langClick() {
      let _url = this.info.poster_list.data[this.showPosterInd].background_poster_url || "";
      if (this.fun.isCPS()) {
        if (this.fun.isIosOrAndroid() === "ios") {
          sharePoster({ body: "sharePoster", url: _url });
        } else {
          downImageAndroid(_url);
        }
      }
    },
    //弹窗方法 start
    showInIint(key) {
      this.show = key;
      this.popupPage = 1;
      this.popupLast = 1;
      this.popupList = [];
    },
    showInMethod() {
      this.showInIint(true);
      this.poplabel = this.labelSelect;
      $http.get("plugin.poster-center.frontend.controllers.index.getLabel", { page: this.popupPage }, " ").then(
        response => {
          if (response.result === 1) {
            console.log(response.data.list);
            this.popupList = response.data.list.data;
            this.popupLast = response.data.list.last_page;
          } else {
            this.$toast(response.msg);
          }
        },
        function (response) {
          console.log(response);
        }
      );
    },
    popupMore() {
      if (this.popupPage >= this.popupLast) return;
      this.popupPage = this.popupPage + 1;
      $http.get("plugin.poster-center.frontend.controllers.index.getLabel", { page: this.popupPage }, " ").then(
        response => {
          if (response.result === 1) {
            this.popupList = this.popupList.concat(response.data.list.data);
          } else {
            this.$toast(response.msg);
          }
        },
        function (response) {
          console.log(response);
        }
      );
    },
    cancelTap() {
      this.poplabel = this.labelSelect;
      this.showInIint(false);
    },
    confirmTap() {
      this.labelSelect = this.poplabel;
      this.showInIint(false);
      this.getData();
    },
    chooseTag(item) {
      if(this.poplabel == item.id){
        this.poplabel = 0;
        return
      }
      this.poplabel = item.id;
    },
    // 弹窗方法 end
    // 生成海报
    creatPoster() {
      if(this.info.poster_list.data[this.showPosterInd].background_poster_url){
        // 有封面就提示长按保存
        this.$dialog.alert({ message: "请长按海报保存" });
        return
      }
      this.posterData = {
        poster_data: null,
        background: {}
      }
      this.toastPoster = Toast({
        duration: -1, // 持续展示 toast
        message: "正在为您生成海报中"
      });
      let id = this.info.poster_list.data[this.showPosterInd].id;
      $http.get("plugin.poster-center.frontend.controllers.index.createPoster", { poster_id: id }, " ").then(
        response => {
          if (response.result === 1) {
            this.posterShow = true;
            this.is_record = response.data.is_record;
            if (response.data.is_record) {
              this.defaultImg = response.data.url;
              this.info.poster_list.data[this.showPosterInd].background_poster_url = response.data.url;
            } else {
              this.defaultImg = "";
              this.posterData.background.type = "background";
              this.posterData.background.src = response.data.model && response.data.model.background ? response.data.model.background : "";
              this.posterData.poster_data = response.data.model && response.data.model.style_data ? response.data.model.style_data : [];
            }
            this.toastPoster.clear();
          } else {
            this.toastPoster.clear();
            this.$toast(response.msg);
          }
        },
        function (response) {
          console.log(response);
          this.toastPoster.clear();
        }
      );
    },
    // 海报生成完成后 子组件传递
    finish(e) {
      this.posterShow = false;
      this.childImgaeBase = e;
      this.info.poster_list.data[this.showPosterInd].background_poster_url = this.childImgaeBase;
      // 上传海报
      if (!this.is_record) {
        this.uoloadPoster();
      }
    },
    dataURItoBlob(dataURI) {
      // 图片转成Buffer---------------------------------
      var byteString = atob(dataURI.split(",")[1]);
      var mimeString = dataURI
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },
    uoloadPoster() {
      let file = new FormData();
      file.append("file", this.dataURItoBlob(this.info.poster_list.data[this.showPosterInd].background_poster_url));
      file.append("poster_id", this.info.poster_list.data[this.showPosterInd].id);
      let uploadImage = this.fun.getRealUrl("plugin.poster-center.frontend.controllers.index.uploadLocal", {});
      axios
        .post(uploadImage, file, {
          headers: { "Content-Type": "multipart/form-data" }
        })
        .then(res => {
          if (res.data.result == 1) {
            console.log(res.data.data.img_url);
            $http.get("plugin.poster-center.frontend.controllers.index.posterRecord", { image: res.data.data.img_url, poster_id: this.info.poster_list.data[this.showPosterInd].id }, " ").then(
              response => {
                if (response.result === 1) {
                  console.log(response.data);
                } else {
                  this.$toast(response.msg);
                }
              },
              function (response) {
                console.log(response);
              }
            );
          } else {
            this.$toast(res.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 选择海报封面
    showPoster(item, index) {
      this.showPosterInd = index;
      this.fmPosterShow = true;
      console.log(item);
    },
    closeFm() {
      // this.posterShow = false;
      // this.posterData = {};
      this.defaultImg = [];
      this.fmPosterShow = false;
    },
    scrollLeft() {
      if (this.showPosterInd == 0) {
        this.$dialog.alert({
          message: "已经是第一张"
        });
        return;
      }
      if (this.showPosterInd > 0) {
        this.showPosterInd = Number(this.showPosterInd) - 1;
        this.posterShow = false;
      }
    },
    scrollRight() {
      // console.log(this.showPosterInd , this.info.poster_list.data.length)
      if (this.showPosterInd >= this.info.poster_list.data.length - 1) {
        this.$dialog.alert({
          message: "已经是最后一张"
        });
        return;
      }
      if (this.showPosterInd < this.info.poster_list.data.length) {
        this.showPosterInd = Number(this.showPosterInd) + 1;
        this.posterShow = false;
      }
    },
    // 搜索方法
    searchMethod() {
      this.getData();
    },
    tapType(id) {
      this.active = id;
      this.getData();
    },
    tapLabel(id) {
      this.labelSelect = id;
      this.getData();
    },
    getData() {
      let json = {
        poster_type: this.active ? this.active : "",
        title: this.keywork,
        label_id: this.labelSelect ? this.labelSelect : ""
      };
      $http.get("plugin.poster-center.frontend.controllers.index.index", json, " ").then(
        response => {
          if (response.result === 1) {
            console.log(response.data);
            this.info = response.data;
            this.isLoadMore = true;
            this.total_page = response.data.poster_list.last_page;
          } else {
            this.$toast(response.msg);
          }
        },
        function (response) {
          console.log(response);
        }
      );
    },
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      if (this.page >= this.total_page) {
        return;
      } else {
        this.page = this.page + 1;
        let json = {
          page: this.page,
          poster_type: this.active ? this.active : "",
          title: this.keywork,
          label_id: this.labelSelect ? this.labelSelect : ""
        };
        $http.get("plugin.poster-center.frontend.controllers.index.index", json, " ").then(
          response => {
            if (response.result === 1) {
              console.log(response.data);
              let myData = response.data.poster_list.data;
              this.info.poster_list.data = this.info.poster_list.data.concat(myData);
              this.isLoadMore = true;
              this.total_page = response.data.poster_list.last_page;
            } else {
              this.$toast(response.msg);
            }
          },
          function (response) {
            console.log(response);
          }
        );
      }
    }
  },
  components: { yz_goodsPoster }
};
</script>
<style lang="scss" scoped>
.poster-popup-class {
  background-color: transparent !important;
}

.fmPoster {
  padding-top: 0.875rem;
  width: 21.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .minimg {
    width: 1.5rem;
    height: 1.5rem;
  }

  .contenBox {
    display: flex;
    flex-direction: column;
    position: relative;

    .closeIcon {
      position: absolute;
      right: -0.875rem;
      top: -0.875rem;
      background-image: url("https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/images%2FposterCenter%2Fclose%402x.png");
      background-repeat: no-repeat;
      background-size: cover;
      width: 1.75rem;
      height: 1.75rem;
      border-radius: 100%;
    }

    .fm {
      // width: 17.5rem;
      // height: 23.31rem;
      width: 100%;
      height: auto;
      border-radius: 0.5rem;
    }

    .btn {
      width: 10.25rem;
      height: 2.25rem;
      border-radius: 0.25rem;
      background: #e95352;
      text-align: center;
      line-height: 2.25rem;
      color: #fff;
      margin: 0 auto;
      margin-top: 1.25rem;
    }

    .btnTxt {
      height: 2.25rem;
      text-align: center;
      line-height: 2.25rem;
      color: #fff;
      margin: 0 auto;
      margin-top: 1.25rem;
    }
  }
}

.posterList {
  padding: 0.75rem;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .posterLis {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    width: 10.72rem;
    border-radius: 1rem;
    background: #fff;
    margin-bottom: 0.75rem;

    img {
      width: 100%;
      height: auto;
      margin-top: 0;
      border-radius: 1rem 1rem 0 0;
    }

    .title {
      width: 100%;
      height: 1.75rem;
      font-size: 0.88rem;
      color: #333;
      line-height: 1.75rem;
      padding-left: 0.5rem;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-align: left;
    }
  }
}

.tabsNav::-webkit-scrollbar {
  display: none;
}

.childTabs .left::-webkit-scrollbar {
  display: none;
}

.newPosterIndex {
  .searchTop {
    background: #fff;

    .van-search {
      padding-bottom: 0;
    }
  }

  .rightBox::-webkit-scrollbar {
    height: 1px !important;
    width: 1px !important;
  }

  .rightBox {
    min-height: 100%;
    background: #fff;
    padding-bottom: 3rem;

    .title {
      font-weight: bold;
      font-size: 1rem;
      color: #333;
      text-align: left;
      padding: 0.75rem;
    }

    .btn {
      display: flex;
      justify-content: flex-end;
      margin-top: 2rem;
      margin-right: 0.75rem;

      .cancel {
        width: 4.25rem;
        height: 2rem;
        line-height: 2rem;
        text-align: center;
        border: 1px solid #e95352;
        border-radius: 0.25rem;
        background: #fff;
        font-size: 0.88rem;
        color: #e95352;
        margin-right: 1.25rem;
      }

      .confirm {
        width: 4.25rem;
        height: 2rem;
        line-height: 2rem;
        text-align: center;
        background: #e95352;
        border-radius: 0.25rem;
        font-size: 0.88rem;
        color: #fff;
      }
    }

    .tipsBox::-webkit-scrollbar {
      display: none;
    }

    .tipsBox {
      max-height: 70vh;
      overflow-y: scroll;
      display: flex;
      margin-top: 0.75rem;
      flex-wrap: wrap;
      padding-left: 0.75rem;

      .tipslis {
        flex-shrink: 0;
        box-sizing: border-box;
        // width: 5.69rem;
        height: 2.03rem;
        background: #f6f6f6;
        border: 0 solid #e95352;
        border-radius: 0.25rem;
        line-height: 2.03rem;
        text-align: center;
        font-size: 0.75rem;
        color: #666;
        padding: 0 0.25rem;
        margin-right: 0.45rem;
        margin-bottom: 0.75rem;
      }

      .tipslis:nth-child(3n) {
        margin-right: 0;
      }

      .modeS {
        border: 1px solid #e95352;
        position: relative;

        .modeSImg {
          position: absolute;
          bottom: 0;
          right: 0;
          width: 1.04rem;
          height: 0.84rem;
          background-image: url("https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/newPoster%2Fselect1.png");
          background-size: cover;
        }
      }
    }
  }

  .childTabs {
    background: #fff;
    padding: 0.75rem;
    display: flex;
    justify-content: space-between;

    .left {
      flex: 1;
      display: flex;
      overflow-x: scroll;

      .tabChild {
        flex-shrink: 0;
        padding: 0.25rem 0.75rem;
        border-radius: 0.78rem;
        background: #f6f6f6;
        margin-right: 1rem;
        font-size: 0.75rem;
        color: #999;
      }

      .mdalabel {
        background: #e95352;
        color: #fff;
      }

      .tabChild:last-child {
        margin-right: 0;
      }
    }

    .right {
      width: 3.88rem;
      flex-shrink: 0;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 0.75rem;
      color: #999;

      img {
        width: 0.75rem;
        height: 0.75rem;
        margin: 0;
      }
    }

    .right::after {
      content: "";
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      width: 1px;
      background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(84, 84, 84, 0.45) 100%);
    }
  }

  .tabsNav {
    background: #fff;
    padding: 0.75rem;
    overflow-x: scroll;
    display: flex;
    justify-content: flex-start;
    padding-bottom: 0;

    .mda {
      color: #e95352;
    }

    .tabsNavLis:last-child {
      margin-right: 0;
    }

    .tabsNavLis {
      flex-shrink: 0;
      margin-right: 1.25rem;
      font-size: 0.88rem;
    }
  }
}
</style>